package com.coalmine.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coalmine.api.domain.ApiDatasourceConf;
import com.coalmine.api.mapper.ApiDatasourceConfMapper;
import com.coalmine.api.service.IApiDatasourceConfService;
import com.coalmine.common.constant.Constants;
import com.coalmine.common.core.redis.RedisCache;
import com.coalmine.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zjx
 * @since 2022-04-08
 */
@Service
public class ApiDatasourceConfServiceImpl extends ServiceImpl<ApiDatasourceConfMapper, ApiDatasourceConf> implements IApiDatasourceConfService {

    @Autowired
    ApiDatasourceConfMapper apiDatasourceConfMapper;

    @Autowired
    private RedisCache redisCache;


    /**
     * 根据id获取数据源默认配置详情
     */
    //@Cacheable(value = "dsconf", key = "#id", unless = "#result == null")
    public ApiDatasourceConf detail(String id) {
        ApiDatasourceConf dsconf = redisCache.getCacheObject(getCacheKey(id));
        if (StringUtils.isNotNull(dsconf)) {
            return dsconf;
        }
        ApiDatasourceConf apiDatasourceConf = apiDatasourceConfMapper.selectById(id);
        if (StringUtils.isNotNull(apiDatasourceConf)) {
            redisCache.setCacheObject(getCacheKey(id), apiDatasourceConf);
            return apiDatasourceConf;
        }
        return null;
    }


    /**
     * 获取所有数据源默认配置列表
     */
    public List<ApiDatasourceConf> getAll() {
        List<ApiDatasourceConf> list = apiDatasourceConfMapper.selectList(null);
        return list.stream()
                .sorted(Comparator.comparing(ApiDatasourceConf::getCreateTime).reversed())
                .collect(Collectors.toList());
    }


    /**
     * 项目启动时，初始化数据源配置到缓存
     */
    @PostConstruct
    public void init() {
        clearDsconfCache();
        loadingDsconfCache();
    }


    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return Constants.API_DSCONF_KEY + configKey;
    }


    /**
     * 加载数据源配置缓存数据
     */
    @Override
    public void loadingDsconfCache() {
        List<ApiDatasourceConf> list = apiDatasourceConfMapper.selectList(null);
        for (ApiDatasourceConf config : list) {
            redisCache.setCacheObject(getCacheKey(config.getId()), config);
        }
    }

    /**
     * 清空数据源配置缓存数据
     */
    @Override
    public void clearDsconfCache() {
        Collection<String> keys = redisCache.keys(Constants.API_DSCONF_KEY + "*");
        redisCache.deleteObject(keys);
    }


}
